package com.wang.mandkey.activity;

import java.net.InetAddress;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.tencent.weibo.api.FriendsAPI;
import com.tencent.weibo.api.TAPI;
import com.tencent.weibo.api.UserAPI;
import com.tencent.weibo.constants.OAuthConstants;
import com.tencent.weibo.oauthv2.OAuthV2;
import com.wang.mandkey.R;
import com.wang.mandkey.bean.OpUser;
import com.wang.mandkey.tool.Tool;
import com.wang.mandkey.utils.StringUtils;

public class ShareQWeiBoActivity extends BaseActivity {

	private String mStringQweibo = "http://t.qq.com/woshiwzyn";
	private Button mButtonAccessMyWeibo;
	private Button mButtonShareQWeibo;
	private Button mButtonWhoMe;
	private EditText mEditTextInput;
	private TextView mTextViewAddress;
	private OAuthV2 oAuth;
	private ProgressDialog mProgressDialog = null;
	private OpUser opu;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		oAuth = (OAuthV2) getIntent().getSerializableExtra("oauth");
		// ==初始化对话框
		mProgressDialog = new ProgressDialog(this);
		mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		mProgressDialog.setTitle(this.getResources().getString(
				R.string.setting_activity_setting_linking));
		mProgressDialog.setCancelable(true);
		mProgressDialog.setMessage(this.getResources().getString(
				R.string.loading));
		// ===初始化完毕

		initView();
		LoadUserInfoTask lut = new LoadUserInfoTask();
		lut.execute(oAuth);
	}

	private void initView() {
		setContentView(R.layout.qshare);
		mButtonAccessMyWeibo = (Button) findViewById(R.id.buttonReceiveMyQWeibo);
		mButtonAccessMyWeibo.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// 收听作者微博
				if (null == opu) {
					mButtonWhoMe.startAnimation(AnimationUtils.loadAnimation(
							ShareQWeiBoActivity.this, R.anim.shake));
				} else {
					ReceiveWeiboTask recv = new ReceiveWeiboTask();
					recv.execute(opu);
				}
				// Tool.startUrl(ShareQWeiBoActivity.this, mStringQweibo);
			}
		});
		mButtonShareQWeibo = (Button) findViewById(R.id.buttonShare);
		mButtonShareQWeibo.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String yousay = mEditTextInput.getText().toString();
				String adres = mTextViewAddress.getText().toString();
				ShareTask shaTask = new ShareTask();
				shaTask.execute(yousay + adres);
			}
		});
		mEditTextInput = (EditText) findViewById(R.id.editTextYourWannaSay);
		mTextViewAddress = (TextView) findViewById(R.id.textViewAddress);
		mTextViewAddress.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Tool.startUrl(ShareQWeiBoActivity.this,
						"http://apk.gfan.com/Product/App286490.html###");
				
			}
		});
		mButtonWhoMe = (Button) findViewById(R.id.buttonWhome);
		mButtonWhoMe.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				LoadUserInfoTask lut = new LoadUserInfoTask();
				lut.execute(oAuth);
			}
		});
	}

	/**
	 * 分享到腾讯weibo
	 * 
	 * @param content
	 * @return
	 * @throws Exception
	 */
	public String shareWeibo(String content) throws Exception {
		String response = null;
		TAPI tAPI = new TAPI(OAuthConstants.OAUTH_VERSION_2_A);
		InetAddress ad = InetAddress.getLocalHost();
		String hadress = ad.getHostAddress();
		response = tAPI.add(oAuth, "json", content, hadress);
		tAPI.shutdownConnection();
		return response;
	}

	/**
	 * 微博分享接口
	 * 
	 * @author Administrator
	 * 
	 */
	class ShareTask extends AsyncTask<String, Void, String> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			mProgressDialog.show();
		}

		@Override
		protected String doInBackground(String... params) {
			String content = (String) (params[0]);
			String ret = null;
			try {
				ret = shareWeibo(content);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return ret;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			mProgressDialog.dismiss();
			if (!StringUtils.isEmpty(result)) {
				try {
					JSONObject jso = new JSONObject(result);
					int ret = jso.getInt("ret");
					if (0 == ret) {
						ToastShow(R.string.share_succ);
						finish();
					} else {
						ToastShow(R.string.share_fail);
					}
				} catch (JSONException e) {
					e.printStackTrace();
					ToastShow(R.string.share_fail);
				}
			} else {
				ToastShow(R.string.share_fail);
			}
		}

	};

	public void ToastShow(int id) {
		Toast.makeText(this, getResources().getString(id), Toast.LENGTH_SHORT)
				.show();
	}

	public void ToastShow(String message) {
		Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		finish();
		return;
	}

	/**
	 * 加载weibo用户个人信息
	 * 
	 * @author Administrator
	 * 
	 */
	class LoadUserInfoTask extends AsyncTask<OAuthV2, Void, String> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			mProgressDialog.show();
		}

		@Override
		protected String doInBackground(OAuthV2... params) {
			String ret = null;
			try {
				OAuthV2 oath2 = (OAuthV2) (params[0]);
				UserAPI userapi = new UserAPI(OAuthConstants.OAUTH_VERSION_2_A);
				ret = userapi.info(oath2, "json");
			} catch (Exception e) {
				ret = null;
			}
			return ret;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			mProgressDialog.dismiss();
			if (!StringUtils.isEmpty(result)) {
				try {
					JSONObject jso = new JSONObject(result);
					int ret = jso.getInt("ret");
					if (ret == 0) {

						JSONObject dataObj = jso.getJSONObject("data");
						String nick = dataObj.getString("nick");
						String openId = dataObj.getString("openid");
						opu = new OpUser();
						opu.setNickName(nick);
						opu.setOpenId(openId);
						updateUserInfo(opu);
						ToastShow("加载用户信息成功！");
						// jso=jso.get("data");
					} else {
						ToastShow("加载用户信息失败");
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}

			}
		}
	}

	/**
	 * 收听作者微博
	 * 
	 * @author Administrator
	 * 
	 */
	class ReceiveWeiboTask extends AsyncTask<OpUser, Void, String> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			mProgressDialog.show();
		}

		@Override
		protected String doInBackground(OpUser... params) {
			String ret = null;
			try {
				OpUser opu = (OpUser) params[0];
				FriendsAPI frendApi = new FriendsAPI(
						OAuthConstants.OAUTH_VERSION_2_A);
				ret = frendApi.add(oAuth, "json", "woshiwzyn", opu.getOpenId());
			} catch (Exception e) {
				ret = null;
			}
			return ret;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			mProgressDialog.dismiss();
			if (!StringUtils.isEmpty(result)) {
				try {
					JSONObject jso = new JSONObject(result);
					int ret = jso.getInt("ret");
					if (0 == ret) {
						// 成功
						ToastShow("操作成功，谢谢关注哟，我会更努力的！");
					} else {
						// 失败
						ToastShow("操作失败，请重试!");
					}
				} catch (JSONException e) {
					e.printStackTrace();
					ToastShow("操作失败，请重试!");
				}
			} else {
				ToastShow("操作失败，请重试!");
			}
		}

	}

	public void updateUserInfo(OpUser opu) {
		mButtonWhoMe.setText(opu.getNickName() + ",谢谢支持哟!");
	}
}
